﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.System.Role
{
    [UseDI(ServiceLifetime.Scoped)]
    public class SysRoleRepository : Repository<SysRole, DefaultDbContext>
    {
        private readonly ILogger logger;

        public SysRoleRepository(DefaultDbContext dbContext, IApplicationContext applicationContext, ILogger<SysRoleRepository> logger)
            : base(dbContext, applicationContext)
        {
            this.logger = logger;
        }

        public bool UpdateRoleStatus(SysRole role, RoleStatus status)
        {
            if (role == null)
                return false;
            var sql_update = Sql.Builder;
            sql_update.Append("Update sys_role SET status = @0 where role_id = @1", status, role.RoleId);//局部更新数据库
            int affectCount = DbContext.Execute(sql_update);
            if (affectCount > 0)
            {
                role.Status = status;
                base.OnUpdated(role);//更新内存数据
                return true;
            }
            return false;
        }

        public IPagedList<SysRole> GetRoles(RoleQuery query, int pageIndex, int pageSize)
        {
            Sql sql = Sql.Builder;
            sql.Select("role_id")
                .From("sys_role");
            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("name Like @0", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");

            sql.Where("is_deleted=0");
            sql.OrderBy("create_time DESC");
            return GetPagingEntities(pageSize, pageIndex, sql);
        }
    }
}